<?php
namespace app\controllers;

use app\commission\ReceivedCommission;
use app\models\order\Order;
use app\models\system\SetBasic;
use app\models\user\UserCommission;

class TimeoutReceivedController extends Controller
{
    /**
     * timeout received
     *
     *  进云仓的到时间会处理,
     *  发货的[提货的], 必须要是发货状态, 到时间才处理
     *
     * 30 2 * * * /usr/bin/curl https://api.sxjk888.top/timeout-received/run
     *
     * /timeout-received/run
     */
    public function actionRun()
    {
        // 不是进云仓的订单
        // 直接发货的, 或者 提货的
        $query = Order::find();
            // ->where([
            //     'or',
            //     ['status' => Order::$statusMapping['WAIT_RECEIVING']],
            //     [
            //         'status' => Order::$statusMapping['PAID'],
            //         'is_store' => 1
            //     ]
            // ]);

        // var_dump($query->createCommand()->getRawSql());exit;


            // 进云仓的也要处理, 因为和提货不重复, 提供只有 地区奖
            // ->andWhere(['is_store' => 0])
        $orders = $query->orderBy(['id' => SORT_DESC])
            ->all();

        // SELECT * FROM `order` WHERE (`status`=2) OR ((`status`=1) AND (`is_store`=1)) ORDER BY `id` DESC
        // $query = Order::find()
        //     ->where([
        //         'or',
        //         ['status' => Order::$statusMapping['WAIT_RECEIVING']],
        //         [
        //             'status' => Order::$statusMapping['PAID'],
        //             'is_store' => 1
        //         ]
        //     ])
        //     ->orderBy(['id' => SORT_DESC]);
        // var_dump($query->createCommand()->getRawSql());exit;

        // var_dump($orders);exit;

        $set = SetBasic::getLastOne();

        $time = time();
        $expired = 3600 * 24 * $set->order_received_timeout;
        // $expired = 1;
        foreach ($orders as $order) {
            $t = $order->create_time;
            $t = strtotime($t);

            if ($time - $t >= $expired) {
                if (ReceivedCommission::done($order->id)) {

                    // 不是进云仓的订单
                    if ($order->is_store == 0) {
                        $order->status = Order::$statusMapping['RECEIVED'];
                    }

                    $order->save();
                }
            }
        }

        return "\n" . date('Y-m-d H:i:s') . ' .......  Done! ' . "\n";
    }

}